package cn.south.campus.common.pay;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2025/1/3 14:47
 */
@Component
public class PayFactory implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private final static Map<String, PayService> PAY_SERVICE_MAP = new HashMap<>();


    public static PayService getPayService(String payMethod) {
        return PAY_SERVICE_MAP.get(payMethod);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (!PAY_SERVICE_MAP.isEmpty()) {
            return;
        }
        String[] namesForType = applicationContext.getBeanNamesForType(PayService.class);
        for (String name : namesForType) {
            PayService payService = applicationContext.getBean(name, PayService.class);
            PAY_SERVICE_MAP.put(payService.method(), payService);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
